<script lang="ts" setup>
import {h, reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {LockOutlined, MailOutlined, SafetyOutlined, UserOutlined} from '@ant-design/icons-vue'
import {useAuthStore} from '@/stores/modules/auth'
import {authApi} from '@/api'
import {handleError, success, warning} from '@/utils/message'
import {createConfirmPasswordRule, FormRules, validate} from '@/utils/validate'
import {USER} from '@/constants/messages'
import type {UserRegisterDTO} from '@/types/dto/auth'

const router = useRouter()
const authStore = useAuthStore()

const loading = ref(false)
const sendingCaptcha = ref(false)
const captchaCountdown = ref(0)

const formState = reactive<UserRegisterDTO>({
  userAccount: '',
  email: '',
  userPassword: '',
  checkPassword: '',
  captcha: ''
})

const rules = {
  userAccount: FormRules.userAccount,
  email: FormRules.email,
  captcha: FormRules.captcha,
  userPassword: FormRules.password,
  checkPassword: [createConfirmPasswordRule(formState, 'userPassword')]
}

const handleSendCaptcha = async () => {
  if (!validate.required(formState.email)) {
    warning('请先输入邮箱地址')
    return
  }

  if (!validate.email(formState.email)) {
    warning(USER.INVALID_EMAIL)
    return
  }

  sendingCaptcha.value = true
  try {
    await authApi.sendCaptcha({email: formState.email})
    success(USER.CAPTCHA_SENT)

    // 开始倒计时
    captchaCountdown.value = 60
    const timer = setInterval(() => {
      captchaCountdown.value--
      if (captchaCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error: any) {
    handleError(error, USER.CAPTCHA_SEND_FAILED)
  } finally {
    sendingCaptcha.value = false
  }
}

const handleRegister = async () => {
  loading.value = true
  try {
    await authStore.register(formState)
    success(USER.REGISTER_SUCCESS)
    // 注册成功后会自动登录并跳转到首页
    await router.push('/')
  } catch (error: any) {
    handleError(error, USER.REGISTER_FAILED)
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-header">
        <h1 class="logo">栖云图库</h1>
        <p class="subtitle">注册账号，开启图片管理之旅</p>
      </div>

      <a-form
          :model="formState"
          :rules="rules"
          class="register-form"
          layout="vertical"
          @finish="handleRegister"
      >
        <a-form-item label="账号" name="userAccount">
          <a-input
              v-model:value="formState.userAccount"
              :prefix="h(UserOutlined)"
              placeholder="4-20字符，仅支持字母数字下划线"
              size="large"
          />
        </a-form-item>

        <a-form-item label="邮箱" name="email">
          <a-input
              v-model:value="formState.email"
              :prefix="h(MailOutlined)"
              placeholder="请输入邮箱地址"
              size="large"
              type="email"
          />
        </a-form-item>

        <a-form-item label="邮箱验证码" name="captcha">
          <a-input
              v-model:value="formState.captcha"
              :maxlength="6"
              :prefix="h(SafetyOutlined)"
              placeholder="请输入6位验证码"
              size="large"
          >
            <template #suffix>
              <a-button
                  :disabled="captchaCountdown > 0 || sendingCaptcha"
                  :loading="sendingCaptcha"
                  type="link"
                  @click="handleSendCaptcha"
              >
                {{ captchaCountdown > 0 ? `${captchaCountdown}秒后重试` : '发送验证码' }}
              </a-button>
            </template>
          </a-input>
        </a-form-item>

        <a-form-item label="密码" name="userPassword">
          <a-input-password
              v-model:value="formState.userPassword"
              :prefix="h(LockOutlined)"
              placeholder="6-20字符"
              size="large"
          />
        </a-form-item>

        <a-form-item label="确认密码" name="checkPassword">
          <a-input-password
              v-model:value="formState.checkPassword"
              :prefix="h(LockOutlined)"
              placeholder="请再次输入密码"
              size="large"
          />
        </a-form-item>

        <a-form-item>
          <a-button
              :loading="loading"
              block
              html-type="submit"
              size="large"
              type="primary"
          >
            注册
          </a-button>
        </a-form-item>

        <a-divider plain>已有账号？</a-divider>

        <a-button block size="large" @click="$router.push('/login')">
          立即登录
        </a-button>
      </a-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@use '@/assets/styles/variables.scss' as *;

.register-container {
  min-height: 100vh;
  @include flex-center;
  background: $gradient-primary;
  padding: $spacing-xl;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -10%;
    width: 800px;
    height: 800px;
    background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
    border-radius: 50%;
    animation: float 20s ease-in-out infinite;
  }

  &::after {
    content: '';
    position: absolute;
    bottom: -30%;
    left: -10%;
    width: 600px;
    height: 600px;
    background: radial-gradient(circle, rgba(255, 255, 255, 0.08) 0%, transparent 70%);
    border-radius: 50%;
    animation: float 25s ease-in-out infinite reverse;
  }

  @keyframes float {
    0%, 100% {
      transform: translate(0, 0);
    }
    50% {
      transform: translate(30px, 30px);
    }
  }
}

.register-box {
  width: 100%;
  max-width: 500px;
  background: white;
  border-radius: $radius-2xl;
  padding: $spacing-3xl $spacing-2xl;
  box-shadow: $shadow-2xl;
  position: relative;
  z-index: 1;

  @include responsive($breakpoint-sm) {
    padding: $spacing-2xl $spacing-xl;
  }

  :deep(.ant-form-item) {
    margin-bottom: $spacing-lg;
  }

  :deep(.ant-form-item-label > label) {
    font-weight: $font-semibold;
    color: $text-primary;
  }

  :deep(.ant-input),
  :deep(.ant-input-password) {
    border-radius: $radius-lg;
    padding: $spacing-md;
    font-size: $font-base;

    &:hover {
      border-color: $primary-light;
    }

    &:focus {
      border-color: $primary-color;
      box-shadow: 0 0 0 2px rgba($primary-color, 0.1);
    }
  }

  :deep(.ant-btn-lg) {
    height: 48px;
    border-radius: $radius-lg;
    font-size: $font-base;
    font-weight: $font-semibold;
  }

  :deep(.ant-btn-primary) {
    background: $gradient-primary;
    border: none;
    box-shadow: $shadow-sm;

    &:hover {
      box-shadow: $shadow-primary;
      transform: translateY(-2px);
    }
  }

  :deep(.ant-divider) {
    margin: $spacing-xl 0;

    .ant-divider-inner-text {
      color: $text-tertiary;
      font-size: $font-sm;
      font-weight: $font-medium;
    }
  }
}

.register-header {
  text-align: center;
  margin-bottom: $spacing-2xl;

  .logo {
    font-size: $font-4xl;
    font-weight: $font-extrabold;
    background: $gradient-primary;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    margin-bottom: $spacing-sm;
    letter-spacing: -0.5px;
  }

  .subtitle {
    color: $text-tertiary;
    font-size: $font-base;
    font-weight: $font-medium;
  }
}
</style>